﻿using UnityEngine;
using System.Collections;

public class Ship : MonoBehaviour {
	public float health = 100;
	public float CollisionDamageScale = 1;
	public Vector3 prevVelocity;

	public float thrustPow = 10;
	public float fuel = 100;
	public float burnRate = 5;
	public float rotationSpeed = 10;
	public float maxHealth = 100;
	public GameObject explosionPrefab;
	public float DistanceFromFloar=0;

	public ParticleSystem thrustersParticles;
	public ParticleSystem thrustersParticlesRight;
	public ParticleSystem thrustersParticlesLeft;
	public ParticleSystem thrustersSUPER;

	public bool thrustUp = false;
	public bool thrustLeft = false;
	public bool thrustRight = false;

	public TriggerArea landingTrigger;

	void Update () 
	{
		thrustUp = (fuel > 0 && Input.GetKey (KeyCode.UpArrow));
		thrustLeft = (fuel > 0 && Input.GetKey (KeyCode.LeftArrow));
		thrustRight = (fuel > 0 && Input.GetKey (KeyCode.RightArrow));
		gameObject.renderer.material.color = Color.Lerp (Color.red, Color.green, health / maxHealth);
		if(health<=0){
			health=0;
			Destroy(gameObject);
		}
	}

	void FixedUpdate()
	{
		if (thrustUp)
		{
			rigidbody.AddForce(transform.up*thrustPow);
			//subtract fuel from the ship when thrusters are on
			fuel -= burnRate * Time.deltaTime;
			thrustersParticles.enableEmission = true;
			if (Input.GetKey(KeyCode.LeftShift))
			{
				rigidbody.AddForce(transform.up*thrustPow);
				fuel -= burnRate * Time.deltaTime;
				thrustersSUPER.enableEmission = true;
			}
			else
			{
				thrustersSUPER.enableEmission = false;
			}
		}
		else
		{
			thrustersParticles.enableEmission = false;
			thrustersSUPER.enableEmission = false;
		}

		if (thrustLeft)
		{
			rigidbody.AddTorque(transform.forward*rotationSpeed);
			thrustersParticlesRight.enableEmission = true;
			fuel -= burnRate * Time.deltaTime * 0.3f;
		}
		else
		{
			thrustersParticlesRight.enableEmission = false;
		}

		if (thrustRight)
		{
			rigidbody.AddTorque(transform.forward*-rotationSpeed);
			thrustersParticlesLeft.enableEmission = true;
			fuel -= burnRate * Time.deltaTime * 0.3f;
		}
		else
		{
			thrustersParticlesLeft.enableEmission = false;
		}
		prevVelocity = rigidbody.velocity;
	}

	void OnCollisionEnter(Collision coll)
	{
		if (coll.gameObject.tag.Equals ("Projectile")) {
				health -= 5;
		} else {
			health-=prevVelocity.magnitude;
		}
	}
}
